package com.shopping.dev.common.util;

import tk.mybatis.mapper.util.StringUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class CookieUtil {

    /**
     *
     * @param request
     * @param resp
     * @param key
     * @param value
     * @param age 失效时间
     * @param isEncode 是否加密
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse resp,String key,String value,int age,boolean isEncode){
        if (value == null){
            value = "";
        }else{
            try {
                value = URLEncoder.encode(value,"utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        }
        Cookie cookie = new Cookie(key,value);
        if (age>0){
            cookie.setMaxAge(age);
        }
        if (request!=null){
            //TODO 设置跨域cookie
            String requestUrl = request.getRequestURL().toString();
            if (requestUrl.contains("http://")){
                requestUrl = requestUrl.replace("http://","");
            }else if(requestUrl.contains("https://")){
                requestUrl = requestUrl.replace("https://","");
            }
            if (requestUrl.contains("/")){
                requestUrl = requestUrl.substring(0,requestUrl.indexOf("/"));
            }
            if (requestUrl.contains(":")){
                requestUrl = requestUrl.substring(0,requestUrl.indexOf(":"));
            }
            cookie.setDomain(requestUrl);
        }
        cookie.setPath("/");
        resp.addCookie(cookie);
    }

    public static void delCookie(HttpServletRequest request,HttpServletResponse resp,String key){
        setCookie(request,resp,key,null,-1,true);
    }
}
